<?php

class wms_mdl_stockapp extends dbeav_model
{

    var $objMath = null;


    /**
     * 根据订单返回发货单详情
     * @param   $order_id
     * @return  array
     * @access  public
     * @author cyyr24@sina.cn
     */
    function getPrintInfo($order_id)
    {
        $sales_material = app::get('material')->model('basic_material');
        $sales_material_ext = app::get('material')->model('basic_material_ext');
        $res = array();
        if (is_array($order_id)) {
            $order_id = implode("','", $order_id);
        }

        $sql = "SELECT 
                wo.stockapp_bn , os.AXCustomer , os.name , wd.deliverytype , wd.logi_name , wdi.bn , SUM(wdi.number) AS number 
                FROM sdb_wms_stockapp wo 
                LEFT JOIN sdb_wms_stockapp_delis wod on (wo.id = wod.stockapp_id)
                LEFT JOIN sdb_wms_delivery wd on (wod.delivery_id = wd.delivery_id)
                LEFT JOIN sdb_wms_delivery_items wdi on (wd.delivery_id = wdi.delivery_id)
                LEFT JOIN sdb_ome_shop os on (wd.shop_id = os.shop_id)
                WHERE wo.id in( '$order_id' ) GROUP BY  wo.stockapp_bn , wdi.bn , os.AXCustomer ";
        $rows = $this->db->select($sql);
        if ($rows) {
            foreach ($rows as $k => $v) {
                $unit = $sales_material->dump(array('material_bn' => $v['bn']), 'bm_id');
                $unit = $sales_material_ext->dump(array('bm_id' => $unit['bm_id']), 'unit');
                $res[$v['stockapp_bn']][$v['bn']]['data'][] = array(
                    'AXCustomer' => $v['AXCustomer'],
                    'name' => $v['name'],
                    'deliverytype' => $v['deliverytype'] == 'deliver' ? '快递' : '门店自提',
                    'logi_name' => $v['logi_name'],
                    'unit' => $unit['unit'],
                    'number' => $v['number'],
                );
                $res[$v['stockapp_bn']][$v['bn']]['deliverytype'] = $v['deliverytype'] == 'deliver' ? '快递' : '门店自提';
                $res[$v['stockapp_bn']][$v['bn']]['logi_name'] = $v['logi_name'];
                $res[$v['stockapp_bn']][$v['bn']]['date'] = date("Y/m/d/ H:i A");
            }
        }
        return ($res);
    }

    public function searchOptions(){
        $parentOptions = parent::searchOptions();
        $childOptions = array(
            'delivery_bn'=>app::get('base')->_('发货单号'),
            'order_bn'=>app::get('base')->_('订单号'),
        );
        return $Options = array_merge($parentOptions,$childOptions);
    }

    public function _filter($filter,$tableAlias=null,$baseWhere=null)
    {   
        if (isset($filter['order_bn']))
        {
            $order_bn = $filter['order_bn'];
            $sql = "SELECT dli.stockapp_id from  sdb_wms_delivery e 
            inner JOIN sdb_ome_delivery od on ( e.outer_delivery_bn = od.delivery_bn )
            inner JOIN sdb_ome_delivery_order odo on ( od.delivery_id = odo.delivery_id )
            inner JOIN sdb_ome_orders os on (odo.order_id = os.order_id)
            inner join sdb_wms_stockapp_delis dli on dli.delivery_bn=e.delivery_bn
            where os.order_bn='$order_bn'";
            
            $_rows = $this->db->select($sql);
            if(!empty($_rows)){
                foreach($_rows as $_orders){
                    $stockapp_id[] = $_orders['stockapp_id'];
                }
                $where .= ' AND id IN ('.implode(',', $stockapp_id).')';
                unset($filter['order_bn']);
            }
        }
        #发货单
        if(isset($filter['delivery_bn'])){
            $delivery_bn = $filter['delivery_bn'];
            $sql = "select stockapp_id from sdb_wms_stockapp_delis  where  delivery_bn= '{$delivery_bn}'";
            
            $_rows = $this->db->select($sql);
            if(!empty($_rows)){
                foreach($_rows as $_orders){
                    $stockapp_id[] = $_orders['stockapp_id'];
                }
                $where .= ' AND id IN ('.implode(',', $stockapp_id).')';
                unset($filter['delivery_bn']);
            }

        }

        return parent::_filter($filter,$tableAlias,$baseWhere).$where;
    }
    //获取明细信息
    function getMxReport($params)
    {
        $this->objMath = kernel::single('eccommon_math');
        set_time_limit(600);
        ini_set('memory_limit', '500M');
        $params['limit_beg'] = isset($params['limit_beg']) ? $params['limit_beg'] : 0;
        $params['limit_end'] = isset($params['limit_end']) ? $params['limit_end'] : 10000;
        if ($params['data_type'] == 'pay') {
            $sqlstr = " wd.status=3 AND sooi.`delete` != 'true' ";
            //$sqlstr .= "  AND soo.pay_status='1'";
            // $sqlstr = ' 0<=wd.status<=3 ';
            if ($params['begin_date']) {
                $sqlstr .= " AND soo.paytime >= " . strtotime($params['begin_date']) . "  ";
            }
            if ($params['end_date']) {
                $sqlstr .= " AND soo.paytime < " . strtotime($params['end_date'] . ' 23:59:59') . "  ";
            }
            if ($params['shop_id']) {
                //$sqlstr .= " AND osh.shop_id ='" . $params['shop_id'] . "'  ";
                $shop_id = implode("','", $params['shop_id']);
                if(empty($shop_id)){
                    $shop_id = $params['shop_id'];
                }
                $sqlstr .= " AND osh.shop_id IN ('" . $shop_id . "')  ";
            }

            if(!empty($params['customer_name'])){
                 $sqlstr .= " AND osh.customername  ='".$params['customer_name']."' ";
            }   

            if(!empty($params['customer_name'])){
                 $sqlstr .= " AND osh.customername  ='".$params['customer_name']."' ";
            }   
            if ($params['materiaBn']) {
                $sqlstr .= " AND sooi.bn = '" . $params['materiaBn'] . "'";
            }

            $sql = " SELECT
                soo.`order_id`,
                soo.`order_bn`,
                soo.`ship_area`,
                soo.`ship_addr`,
                soo.`status` AS 'orders_status',
                soo.`pay_status`,
                soo.`paytime`,
                soo.`mark_text` ,
                soo.`total_amount`,
                soo.`cost_item`,
                soo.`cost_freight`,
                soo.`cost_protect`,
                soo.`cost_tax`,
                soo.`discount`,
                soo.`pmt_goods`,
                soo.`pmt_order`,
                soo.`payed`,
                soo.`createway`,


                sooi.`name` AS 'order_items_name',
                sooi.`bn` AS 'order_items_bn',
                sooi.`amount` AS 'order_items_amount',
                sooi.`cost` AS 'order_items_cost',
                sooi.`price` AS 'order_items_price',
                sooi.`sale_price` AS 'order_items_sale_price',
                sooi.`pmt_price` AS 'order_items_pmt_price',
                sooi.`nums` AS 'order_items_nums' ,
                sooi.`sendnum` AS 'order_items_sendnum' ,
                sooi.`return_num` AS 'order_items_return_num' ,

                sodid.`amount` AS 'delivery_detail_amount' ,
                sodid.`price` AS 'delivery_detail_price' ,
                sodid.`number` AS 'delivery_detail_number' ,
                sodid.order_item_id,

                osh.`name` AS 'shop_name' ,
                wd.`delivery_id` AS 'wms_delivery_id',
                wdb.`logi_no` ,
                wd.`logi_name` ,
                wd.`status` ,
                wd.`delivery_bn` ,
                wd.`delivery_time`,
                wof.`last_modify`,
                smbme.`unit` AS 'unit' , '' AS '退货确认时间'

                FROM sdb_ome_delivery_items_detail AS sodid
                LEFT JOIN sdb_ome_order_items AS sooi ON sodid.order_item_id = sooi.item_id
                LEFT JOIN sdb_ome_delivery_items AS sodi ON sodi.item_id = sodid.delivery_item_id
                LEFT JOIN sdb_ome_delivery AS sod ON sod.delivery_id = sodi.delivery_id
                LEFT JOIN sdb_ome_orders AS soo ON soo.order_id = sodid.order_id
                LEFT JOIN sdb_ome_shop AS osh ON soo.shop_id = osh.shop_id
                LEFT JOIN sdb_wms_delivery AS wd ON wd.outer_delivery_bn = sod.delivery_bn
                LEFT JOIN sdb_wms_stockapp_delis AS wof ON (wof.delivery_id = wd.delivery_id)
                LEFT JOIN sdb_wms_delivery_bill AS wdb ON (wdb.delivery_id = wd.delivery_id)
                LEFT JOIN sdb_material_basic_material_ext AS smbme ON (smbme.bm_id = sodid.product_id)
                WHERE ". $sqlstr . " AND (sod.parent_id =0 or sod.parent_id is NULL)  AND soo.process_status != 'cancel' AND soo.status != 'dead' AND soo.is_fail='false'
                ORDER BY soo.order_id ASC
                 LIMIT " . $params['limit_beg'] . "," . $params['limit_end'];
                 //echo $sql.'<hr>';
        }

        if ($params['data_type'] == 'send') {
            $sqlstr = " wd.status=3 AND sooi.`delete` != 'true' ";
            if ($params['begin_date']) {
                $sqlstr .= " AND wd.delivery_time >= " . strtotime($params['begin_date']) . "  ";
            }
            if ($params['end_date']) {
                $sqlstr .= " AND wd.delivery_time < " . strtotime($params['end_date'] . ' 23:59:59') . "  ";
            }
            if ($params['shop_id']) {
                //$sqlstr .= " AND osh.shop_id ='" . $params['shop_id'] . "'  ";
                $shop_id = implode("','", $params['shop_id']);
                if(empty($shop_id)){
                    $shop_id = $params['shop_id'];
                }
                $sqlstr .= " AND osh.shop_id IN ('" . $shop_id . "')  ";
            }

            if(!empty($params['customer_name'])){
                 $sqlstr .= " AND osh.customername  ='".$params['customer_name']."' ";
            }   
            
            if(!empty($params['customer_name'])){
                 $sqlstr .= " AND osh.customername  ='".$params['customer_name']."' ";
            } 
            if ($params['materiaBn']) {
                $sqlstr .= " AND sooi.bn = '" . $params['materiaBn'] . "'";
            }
            $sql = " SELECT
                soo.`order_id`,
                soo.`order_bn`,
                soo.`ship_area`,
                soo.`ship_addr`,
                soo.`status` AS 'orders_status',
                soo.`pay_status`,
                soo.`paytime`,
                soo.`mark_text` ,
                soo.`total_amount`,
                soo.`cost_item`,
                soo.`cost_freight`,
                soo.`cost_protect`,
                soo.`cost_tax`,
                soo.`discount`,
                soo.`pmt_goods`,
                soo.`pmt_order`,
                soo.`payed`,
                soo.`createway`,

                sooi.`name` AS 'order_items_name',
                sooi.`bn` AS 'order_items_bn',
                sooi.`amount` AS 'order_items_amount',
                sooi.`cost` AS 'order_items_cost',
                sooi.`price` AS 'order_items_price',
                sooi.`sale_price` AS 'order_items_sale_price',
                sooi.`pmt_price` AS 'order_items_pmt_price',
                sooi.`nums` AS 'order_items_nums' ,
                sooi.`sendnum` AS 'order_items_sendnum' ,
                sooi.`return_num` AS 'order_items_return_num' ,

                sodid.`amount` AS 'delivery_detail_amount' ,
                sodid.`price` AS 'delivery_detail_price' ,
                sodid.`number` AS 'delivery_detail_number' ,
                sodid.order_item_id,

                osh.`name` AS 'shop_name' ,
                wd.`delivery_id` AS 'wms_delivery_id',
                wdb.`logi_no` ,
                wd.`logi_name` ,
                wd.`status` ,
                wd.`delivery_bn` ,
                wd.`delivery_time`,
                wof.`last_modify`,
                smbme.`unit` AS 'unit' , '' AS '退货确认时间'

                FROM sdb_ome_delivery_items_detail AS sodid
                LEFT JOIN sdb_ome_order_items AS sooi ON sodid.order_item_id = sooi.item_id
                LEFT JOIN sdb_ome_delivery_items AS sodi ON sodi.item_id = sodid.delivery_item_id
                LEFT JOIN sdb_ome_delivery AS sod ON sod.delivery_id = sodi.delivery_id
                LEFT JOIN sdb_ome_orders AS soo ON soo.order_id = sodid.order_id
                LEFT JOIN sdb_ome_shop AS osh ON soo.shop_id = osh.shop_id
                LEFT JOIN sdb_wms_delivery AS wd ON wd.outer_delivery_bn = sod.delivery_bn
                LEFT JOIN sdb_wms_stockapp_delis AS wof ON (wof.delivery_id = wd.delivery_id)
                LEFT JOIN sdb_wms_delivery_bill AS wdb ON (wdb.delivery_id = wd.delivery_id)
                LEFT JOIN sdb_material_basic_material_ext AS smbme ON (smbme.bm_id = sodid.product_id)
                WHERE " . $sqlstr . " AND (sod.parent_id =0 or sod.parent_id is NULL) AND soo.process_status != 'cancel' AND soo.status != 'dead' AND soo.is_fail='false'
                ORDER BY soo.order_id ASC
                LIMIT " . $params['limit_beg'] . "," . $params['limit_end'];
                 //echo $sql.'<hr>';

        }

        $delivery = app::get('wms')->model('delivery');

		//echo $sql ;exit;
        $rows = $this->db->select($sql);
        $res = array();
        if ($rows) {
            foreach ($rows as $k => $v) {
                $remark = '';
                if ($v['mark_text']) {
                    $v['mark_text'] = unserialize($v['mark_text']);
                    foreach ($v['mark_text'] as $value) {
                        $remark .= implode(' ', $value);
                    }
                }
                //备注
                $sql = " SELECT GROUP_CONCAT(pmt_describe SEPARATOR ' | ') as remark "
                    . "FROM sdb_ome_order_pmt where order_id = '" . $v['order_id'] . "' group by order_id ";
                $rows = $this->db->select($sql);
                if(!empty($rows[0])) {
                    $remark .= ' 优惠方案：' . $rows[0]['remark'];
                }
                if(false) {  //订单级别优惠平摊到每个SKU上
                    //获取退款金额
                    $refunds_sql = " SELECT IFNULL( SUM(money), 0) AS 'money' FROM sdb_ome_refunds WHERE status ='succ' AND order_id = '" . $v['order_id'] . "'";
                    $refunds_money = $this->db->selectRow($refunds_sql);

                    //按照货品总数量计算均摊
                    $bn_quantity_sql = " SELECT SUM(quantity) AS 'nums' FROM sdb_ome_order_objects WHERE order_id = '" . $v['order_id'] . "' AND `delete` = 'false' "; //AND obj_type = 'goods'
                    $bn_quantity_nums = $this->db->selectrow($bn_quantity_sql);
                    $calc_nums = $bn_quantity_nums;

                    //订单明细货品优惠总金额摊分到该SKU上是多少
                    $order_items_pmt_price_single = $this->objMath->number_div(array($v['order_items_pmt_price'], $v['order_items_nums']));

                    //订单促销优惠平均摊分到每个SKU上是多少
                    $order_items_pmt_bn_single = $this->objMath->number_div(array($v['pmt_order'], $calc_nums['nums']));
                    $order_items_pmt_bn_sum = $this->objMath->number_multiple(array($order_items_pmt_bn_single, $v['order_items_nums']));

                    //订单快递费用平均摊分到每个货品上是多少
                    $order_items_cost_freight_bn_single = $this->objMath->number_div(array($v['cost_freight'], $calc_nums['nums']));
                    $order_items_cost_freight_bn_sum = $this->objMath->number_multiple(array($order_items_cost_freight_bn_single, $v['order_items_nums']));

                    //订单折扣平均摊分到每个货品上是多少
                    $order_items_discount_bn_single = $this->objMath->number_div(array($v['discount'], $calc_nums['nums']));
                    $order_items_discount_bn_sum = $this->objMath->number_multiple(array($order_items_discount_bn_single, $v['order_items_nums']));

                    //订单保价费用摊分到每个货品上是多少
                    $order_items_cost_protect_single = -$this->objMath->number_div(array($v['cost_protect'], $calc_nums['nums']));
                    $order_items_cost_protect_sum = $this->objMath->number_multiple(array($order_items_cost_protect_single, $v['order_items_nums']));

                    //订单保价费用摊分到每个货品上是多少
                    $order_items_cost_tax_single = -$this->objMath->number_div(array($v['cost_tax'], $calc_nums['nums']));
                    $order_items_cost_tax_sum = $this->objMath->number_multiple(array($order_items_cost_tax_single, $v['order_items_nums']));

                    //发货单价
                    $delivery_detail_pmt_price = $this->objMath->number_minus(array($v['delivery_detail_price'], $order_items_pmt_bn_single));
                    $delivery_detail_pmt_amount = $this->objMath->number_multiple(array($delivery_detail_pmt_price, $v['delivery_detail_number']));

                    //单个货品优惠总金额
                    $order_items_pmt_single = $this->objMath->number_plus(array($order_items_pmt_price_single, $order_items_pmt_bn_single, $order_items_discount_bn_single));

                }
                else
                { //按每个货品对应金额比例摊分订单的优惠

                    $refunds_info = array();
                    if(in_array($v['pay_status'], array('4', '5'))) {
                        //获取退款金额
                        $refunds_sql = " SELECT IFNULL( SUM(money), 0) AS 'money' FROM sdb_ome_refunds WHERE status ='succ' AND  order_id = '" . $v['order_id'] . "'";
                        $refunds_money = $this->db->selectRow($refunds_sql);

                        $refunds_sql = " SELECT `refund_bn`,`money`,`t_sent` FROM sdb_ome_refunds WHERE status ='succ' AND  order_id = '" . $v['order_id'] . "'";
                        $refunds_money_2 = $this->db->select($refunds_sql);
                        foreach ($refunds_money_2 as $key_refunds => $value_refunds) {
                            $refunds_info[] = "退款单号：" . $value_refunds['refund_bn'];
                            $refunds_info[] = "退款金额：" . $value_refunds['money'];
                            $refunds_info[] = "退款时间：" . date('Y-m-d H:i:s', $value_refunds['t_sent']);
                        }
                        $refunds_info_string = implode(',', $refunds_info);
                    }else{
                        $refunds_info_string = '';
                    }

                    //获取货品总数量
                    $bn_quantity_sql = " SELECT SUM(quantity) AS 'nums' FROM sdb_ome_order_objects WHERE order_id = '" . $v['order_id'] . "' AND `delete` = 'false' "; //AND obj_type = 'goods'
                    $bn_quantity_nums = $this->db->selectrow($bn_quantity_sql);
                    $calc_nums = $bn_quantity_nums;

                    //订单明细货品优惠总金额摊分到该SKU上是多少
                    $order_items_pmt_price_single = $this->objMath->number_div(array($v['order_items_pmt_price'], $v['order_items_nums']));

                    //订单快递费用平均摊分到每个货品上是多少
                    $order_items_cost_freight_bn_single = $this->objMath->number_div(array($v['cost_freight'], $calc_nums['nums']));
                    $order_items_cost_freight_bn_sum = $this->objMath->number_multiple(array($order_items_cost_freight_bn_single, $v['delivery_detail_number']));

                    //订单折扣平均摊分到每个货品上是多少
                    $order_items_discount_bn_single = -$this->objMath->number_div(array($v['discount'], $calc_nums['nums']));
                    $order_items_discount_bn_sum = $this->objMath->number_multiple(array($order_items_discount_bn_single, $v['order_items_nums']));

                    //订单保价费用摊分到每个货品上是多少
                    $order_items_cost_protect_single = -$this->objMath->number_div(array($v['cost_protect'], $calc_nums['nums']));
                    $order_items_cost_protect_sum = $this->objMath->number_multiple(array($order_items_cost_protect_single, $v['order_items_nums']));

                    //订单保价费用摊分到每个货品上是多少
                    $order_items_cost_tax_single = -$this->objMath->number_div(array($v['cost_tax'], $calc_nums['nums']));
                    $order_items_cost_tax_sum = $this->objMath->number_multiple(array($order_items_cost_tax_single, $v['order_items_nums']));


                    //订单促销优惠按比例来分摊
                    //销售总价*(订单促销金额+折扣金额)/((订单支付金额+订单促销金额+折扣金额)*货品数量)
                    $pmt_discount = $this->objMath->number_minus(array($v['pmt_order'], $v['discount']));
                    $pmt_discount_payed = $this->objMath->number_plus(array($pmt_discount, $v['payed']));
                    $sale_pmt = $this->objMath->number_multiple(array($pmt_discount, $v['order_items_sale_price'])); //销售总价*(订单促销金额+折扣金额)
                    $pmt_nums = $this->objMath->number_multiple(array($pmt_discount_payed, $v['order_items_nums'])); //(订单支付金额+订单促销金额+折扣金额)*货品数量
                    $order_items_pmt_bn_single = $this->objMath->number_div(array($sale_pmt, $pmt_nums));
                    $order_items_pmt_bn_sum = $this->objMath->number_multiple(array($order_items_pmt_bn_single, $v['order_items_nums']));

                    //发货单价
                    $delivery_detail_pmt_price = $this->objMath->number_minus(array($v['delivery_detail_price'], $order_items_pmt_bn_single));
                    $delivery_detail_pmt_amount = $this->objMath->number_multiple(array($delivery_detail_pmt_price, $v['delivery_detail_number']));

                    //单个货品优惠总金额
                    $order_items_pmt_single = $this->objMath->number_plus(array($order_items_pmt_price_single, $order_items_pmt_bn_single, $order_items_discount_bn_single));
                }

                $axorderno = $axshipno = array(); $create_time ='';
                $deliverynote_sql = "SELECT wdl.`axorderno`,wdl.`axshipno` ,wdn.`create_time` from  sdb_wms_deliverynote_line AS wdl
                LEFT JOIN sdb_wms_deliverynote AS wdn ON (wdl.deliverynote_id = wdn.id)
                WHERE   wdl.delivery_id = ".$v['wms_delivery_id'];
                $deliverynote_rows = $this->db->select($deliverynote_sql);
                foreach ($deliverynote_rows as $key_deliverynote => $value_deliverynote) {
                    $axorderno[] = $value_deliverynote['axorderno'];
                    $axshipno[] = $value_deliverynote['axshipno'];
                    //$create_time = date('Y-m-d H:i:s', $value_deliverynote['create_time']);
                }
                $stockapp_sql = "SELECT wd.create_time from  sdb_wms_stockapp AS wd 
                LEFT JOIN sdb_wms_stockapp_delis  wod ON (wod.stockapp_id = wd.id) 
                WHERE wod.delivery_id = ".$v['wms_delivery_id'];
                $deliverynote_rows = $this->db->select($stockapp_sql);
                $create_time =  date('Y-m-d H:i:s', $deliverynote_rows[0]['create_time']);
                
                $axorderno_string = implode(',', $axorderno);
                $axshipno_string = implode(',', $axshipno);
                $create_time_string = $create_time;
                switch ($v['createway']) {
                    case 'matrix':
                        $v['createway']='平台获取';
                        break;
                    case 'local':
                        $v['createway']='手工新建';
                        break;
                    case 'import':
                        $v['createway']='批量导入';
                        break;
                    case 'after':
                        $v['createway']='售后自建';
                        break;                 
                    default:
                        $v['createway']='';
                        break;
                }
                $res[] = array(
                    //【订单总表级别金额】
                    'order_id' => $v['order_id'],//订单ID
                    'order_bn' => $v['order_bn'],//订单编号
                    'createway' => $v['createway'],//订单生成类型
                    'ship_addr' => $v['ship_addr'],//地区
                    'ship_area' => $v['ship_area'],//地址
                    'orders_status' => $v['orders_status'],//订单状态
                    'pay_status' => $this->get_pay_status($v['pay_status']),       //订单支付状态
                    'paytime' => $v['paytime'] ? date("Y-m-d H:m:s", $v['paytime']) : '',                                    //订单支付时间
                    //'mark_text' => $v['mark_text'],
                    'total_amount' => $v['total_amount'],                          //订单总额
                    'cost_item'    => $v['cost_item'],                             //订单物料总额
                    'cost_freight' => $v['cost_freight'],                          //配送费用
                    'cost_protect' => $v['cost_protect'],                          //保价费用
                    'cost_tax'     => $v['cost_tax'],                              //税金
                    'discount'     => -$v['discount'],                              //折扣
                    'pmt_goods'    => $v['pmt_goods'],                             //商品促销优惠
                    'pmt_order'    => $v['pmt_order'],                             //订单促销优惠
                    'payed'        => $v['payed'],                                 //已支付金额
                    'refunds_money'  => $refunds_money['money'],                                 //退款金额

                    //【订单明细表级别金额】
                    'order_items_name' => $v['order_items_name'],                  //宝贝名称
                    'order_items_bn'   => $v['order_items_bn'],                    //货号
                    'order_items_amount'       => $v['order_items_amount'],        //订单明细货品总金额 货品小计 = 单价 x 数量
                    'order_items_cost'         => $v['order_items_cost'],          //订单明细货品成本价
                    'order_items_price'        => $v['order_items_price'],         //订单明细货品购买单价
                    'order_items_sale_price'   => $v['order_items_sale_price'],    //订单明细货品销售总价
                    'order_items_pmt_price'    => $v['order_items_pmt_price'],     //订单明细货品优惠总金额
                    'order_items_pmt_price_single'    => $order_items_pmt_price_single,     //订单明细货品优惠摊分到每个SKU金额
                    'order_items_pmt_bn_sum'   => $order_items_pmt_bn_sum,         //订单优惠摊分到每个货品金额
                    'order_items_pmt_bn_sigle' => $order_items_pmt_bn_single,       //订单优惠摊分到每个SKU金额
                    'order_items_cost_freight_bn_sum' => $order_items_cost_freight_bn_sum,       //配送费用摊分到每个货品金额
                    'order_items_cost_freight_bn_sigle' => $order_items_cost_freight_bn_single,   //配送费用摊分到每个SKU金额
                    'order_items_discount_bn_sum' => $order_items_discount_bn_sum,           //折扣费用摊分到每个货品金额
                    'order_items_discount_bn_sigle' => $order_items_discount_bn_single,       //折扣费用摊分到每个SKU金额
                    'order_items_cost_protect_sum' => $order_items_cost_protect_sum,       //保价费用摊分到每个SKU金额
                    'order_items_cost_protect_single' => $order_items_cost_protect_single,       //保价费用摊分到每个SKU金额
                    'order_items_cost_tax_sum' => $order_items_cost_tax_sum,       //税金费用摊分到每个SKU金额
                    'order_items_cost_tax_single' => $order_items_cost_tax_single,       //税金费用摊分到每个SKU金额
                    'order_items_pmt_single' => $order_items_pmt_single, //订单明细货品优惠总金额

                    'order_items_nums'         => $v['order_items_nums'],          //订单明细货品总数量
                    'order_items_sendnum'      => $v['order_items_sendnum'],       //订单明细货品已发货数量
                    'order_items_return_num'   => $v['order_items_return_num'],    //订单明细货品已退货数量

                    //【发货明细详情表级别金额】
                    'delivery_detail_amount'   => $v['delivery_detail_amount'],    //商品优惠后发货明细货品销售总金额
                    'delivery_detail_price'   => $v['delivery_detail_price'],      //发货明细货品销售单价
                    'delivery_detail_pmt_amount'   => $delivery_detail_pmt_amount,      //发货优惠后销售总金额
                    'delivery_detail_pmt_price'   => $delivery_detail_pmt_price, //发货明细货品优惠后的金额
                    'delivery_detail_cost_freight' => $this->objMath->number_multiple(
                        array(
                            $order_items_cost_freight_bn_single,
                            $v['delivery_detail_number']
                        )
                    ), //发货明细配送费用金额
                    'delivery_detail_number'   => $v['delivery_detail_number'],    //发货明细货品总数量
                    'shop_name' => $v['shop_name'],                                //店铺名称
                    'logi_no' => $v['logi_no'],                                    //快递单号
                    'logi_name' => $v['logi_name'],                                //快递单号
                    'status' => $delivery->get_process_status($v['status']),       //进度状态
                    'delivery_bn' => $v['delivery_bn'],                            //发货单号
                    'axorderno' => $axorderno_string,                                //AX销售订单号
                    'axshipno' => $axshipno_string,                                  //AX送货单号
                    'create_time' => $create_time_string,//备货时间
                    'ax_time' => $v['delivery_time'] ? date("Y-m-d H:m:s", $v['delivery_time']) : '',//订单发货时间
                    'unit' => $v['unit'],

                    'order_item_number' => $v['order_item_number'],                //订单明细货品总数量
                    'number' => $v['delivery_detail_number'],                      //订单数量
                    'axnumber' => $v['delivery_detail_number'],                    //备货数量
                    'd_number' => $v['delivery_detail_number'],                    //发货数量
                    'd_price' => $v['price'],                                      //发货单价
                    'd_sale_price' => $v['sale_price'],                            //发货金额

                    't_ready' => $refunds_info_string,
                    't_count' => $v['back_number'],                            //退款数量
                    't_money' => $refunds_money['money'],                          //退款金额
                    'remark' => $remark ? '订单备注：' . $remark : '',              //订单备注
                );

                unset($axorderno_string);
                unset($axshipno_string);
                unset($create_time_string);
                unset($delivery_detail_pmt_amount);
                unset($delivery_detail_pmt_price);
                unset($order_items_pmt_price_single);
                unset($order_items_pmt_bn_sum);
                unset($order_items_pmt_bn_single);
                unset($order_items_cost_freight_bn_sum);
                unset($order_items_cost_freight_bn_single);
                unset($order_items_discount_bn_sum);
                unset($order_items_discount_bn_single);
                unset($order_items_pmt_single);
                unset($refunds_info);
                unset($refunds_info_string);
                unset($refunds_money);
                unset($remark);
            }
        }
        return ($res);
    }

    //获取总数量
    function getCount($params)
    {
        set_time_limit(600);
        ini_set('memory_limit', '500M');

        if ($params['data_type'] == 'pay') {
            $sqlstr = "AND wd.status=3 AND sooi.`delete` != 'true' ";

            if ($params['begin_date']) {
                $sqlstr .= " AND soo.paytime >= " . strtotime($params['begin_date']) . "  ";
            }
            if ($params['end_date']) {
                $sqlstr .= " AND soo.paytime < " . strtotime($params['end_date'] . ' 23:59:59') . "  ";
            }
        }

        if ($params['data_type'] == 'send') {
            $sqlstr = "AND  wd.status=3 AND sooi.`delete` <> 'true' ";
            if ($params['begin_date']) {
                $sqlstr .= " and wd.delivery_time >= " . strtotime($params['begin_date']) . "  ";
            }
            if ($params['end_date']) {
                $sqlstr .= " and wd.delivery_time < " . strtotime($params['end_date'] . ' 23:59:59') . "  ";
            }
        }

        if(isset($params['materiaBn']) && !empty($params['materiaBn'])){
            $sqlstr .= "AND smbm.material_name='".trim($params['materiaBn'])."'";
        }
        if (isset($params['materiaBn']) && !empty($params['shop_id'])) {
                //$sqlstr .= " and osh.shop_id ='" . $params['shop_id'] . "'  ";
            $shop_id = implode("','", $params['shop_id']);
            if(empty($shop_id)){
                $shop_id = $params['shop_id'];
            }
            $sqlstr .= " AND osh.shop_id IN ('" . $shop_id . "')  ";
        }
        if(!empty($params['customer_name'])){
             $sqlstr .= " AND osh.customername  ='".$params['customer_name']."' ";
        }
        $sql = "SELECT
                    COUNT(1) as  `_count`
                    FROM sdb_ome_delivery_items_detail AS sodid
                    LEFT JOIN sdb_ome_order_items AS sooi ON sodid.order_item_id = sooi.item_id
                    LEFT JOIN sdb_ome_delivery_items AS sodi ON sodi.item_id = sodid.delivery_item_id
                    LEFT JOIN sdb_ome_delivery AS sod ON sod.delivery_id = sodi.delivery_id
                    LEFT JOIN sdb_ome_orders AS soo ON soo.order_id = sodid.order_id
                    LEFT JOIN sdb_ome_shop AS osh ON soo.shop_id = osh.shop_id
                    LEFT JOIN sdb_wms_delivery AS wd ON wd.outer_delivery_bn = sod.delivery_bn
                    LEFT JOIN sdb_wms_stockapp_delis AS wof ON (wof.delivery_id = wd.delivery_id)
                    LEFT JOIN sdb_wms_delivery_bill AS wdb ON (wdb.delivery_id = wd.delivery_id)
                    LEFT JOIN sdb_material_basic_material_ext AS smbme ON (smbme.bm_id = sodid.product_id)
                    LEFT JOIN sdb_material_basic_material AS smbm ON (smbme.bm_id = smbm.bm_id)
                    WHERE 1=1 " . $sqlstr . " AND (sod.parent_id =0 or sod.parent_id is NULL)
                    ORDER BY soo.order_id ASC ";
        $rows = $this->db->select($sql);
        return $rows;
    }

    function get_pay_status($pay_status_key){
        $pay_status = array(
            '0' => '未支付',
            '1' => '已支付',
            '2' => '处理中',
            '3' => '部分付款',
            '4' => '部分退款',
            '5' => '全额退款',
            '6' => '退款申请中',
            '7' => '退款中',
            '8' => '支付中'
        );

        return $pay_status[$pay_status_key];
    }

    var $has_export_cnf = true;
    public $export_name = '备货申请表';

    function getselectdata($filter, $offset, $limit)
    {
        $list = $this->getList('*', $filter, $offset, $limit);
        $apapiMdl = app::get('wms')->model('stockapp_delis');
        $listData=array();
        $i=0;
        foreach ($list as $k => $v) 
        {
            $apapiata = $apapiMdl->getList("*",array('stockapp_id'=>$v['id']));
            $listData[$i]['stockapp_bn'] = ($v['stockapp_bn'] ? $v['stockapp_bn'] : '-');
            $listData[$i]['pickinglist_bn'] = ($v['pickinglist_bn'] ? $v['pickinglist_bn'] : '-');
            $listData[$i]['status'] = ($v['status'] ? $v['status'] : '-');
            $listData[$i]['operator'] = ($v['operator'] ? $v['operator'] : '-');
            $listData[$i]['create_time'] = ($v['create_time'] ? $v['create_time'] : '-');
            $listData[$i]['remark'] = ($v['remark'] ? $v['remark'] : '-');
            $listData[$i]['sumqty'] = count($apapiata);
            $i=$i+1;
        }
        return $listData;
    }

    function getExportDataByCustom($fields, $filter, $has_detail, $curr_sheet, $start, $end)
    {
        if($curr_sheet == 1){
            $title = array();
            foreach ($this->io_title('apapi') as $k => $v) {
                $title[] = mb_convert_encoding($v, 'GBK', 'UTF-8');
            }
            $data['content']['main'][0] = '"' . implode('","', $title) . '"';
        }
        $list = $this->getselectdata($filter, $start, $end);
        $status_arr= array (
            'unconfirmed' => '新建',
            'confirmed' => '已提交',
            'approved' => '已审核',
          );
        foreach ($list as $key => $value) 
        {
            $list[$key]['create_time'] = $value['create_time']?date('Y-m-d H:i:s', $value['create_time']):'';
            $list[$key]['status'] = $status_arr[$value['status']];
            
        }
        foreach ($list as $k => $aFilter) {
            $exptmp_data = array();
            foreach ($aFilter as $col => $val) {
                $aFilter[$col] = mb_convert_encoding($aFilter[$col], 'GBK', 'UTF-8');
                $exptmp_data[] = $aFilter[$col];
            }
            $data['content']['main'][] = implode(',', $exptmp_data);
        }
        return $data;
    }
    function io_title($filter, $ioType = 'csv')
    {
        switch ($filter) {
            case 'apapi':
                $this->oSchema['csv'][$filter] = array(
                    '*:申请单号' => 'stockapp_bn',
                    '*:审批单号' => 'pickinglist_bn',                    
                    '*:状态' => 'status',             
                    '*:操作员' => 'operator',
                    '*:备货日期' => 'create_time',
                    '*:备注' => 'remark',
                    '*:明细数量' => 'sumqty',
                );
                break;
        }
        $this->ioTitle[$ioType][$filter] = array_keys($this->oSchema[$ioType][$filter]);
        return $this->ioTitle[$ioType][$filter];
    }
    public function get_schema_export()
    {
        $schema = array(
            'columns' => array(
                'stockapp_bn' => array (
                    'type' => 'varchar(50)',
                    'required' => false,
                    'editable' => false,
                    'label' => '申请单号',
                    'in_list' => true,
                    'default_in_list' => true,
                    'searchtype' => 'has',
                    'filtertype' => 'normal',
                    'filterdefault' => true,
                    'width' => 150,
                    'order' => 20
                ),
                'pickinglist_bn' => array (
                    'type' => 'varchar(50)',
                    'required' => false,
                    'editable' => false,
                    'label' => '审批单号',
                    'in_list' => true,
                    'default_in_list' => true,
                    'searchtype' => 'has',
                    'filtertype' => 'normal',
                    'filterdefault' => true,
                    'width' => 150,
                    'order' => 20
                ),
                'status' => array (
                    'type' => 'varchar(32)',
                    'default' => 0,
                    'required' => false,
                    'label' => '状态',
                    'in_list' => true,
                    'default_in_list' => true,
                    'width' => 65,
                    'order' => 50
                ),
                'operator' => array (
                    'type' => 'varchar(32)',
                    'required' => false,
                    'editable' => false,
                    'label' => '操作员',
                    'in_list' => true,
                    'default_in_list' => true,
                    'width' => 150,
                    'order' => 200
                ),
                'create_time' => array(
                    'type' => 'time',
                    'label'=>'备货日期',
                    'in_list' => false,
                    'default_in_list' => false,
                    'order' => 130,
                ),
                'remark' => array (
                    'type' => 'varchar(50)',
                    'required' => false,
                    'editable' => false,
                    'label' => '备注',
                    'in_list' => false,
                    'default_in_list' => false,
                    'width' => 150,
                    'order' => 40
                ),
                'sumqty' => array (
                    'type' => 'varchar(32)',
                    'required' => false,
                    'editable' => false,
                    'label' => '明细数量',
                    'in_list' => true,
                    'default_in_list' => true,
                    'width' => 150,
                    'order' => 200
                ),
            ),
            'idColumn' => 'name',
            'in_list' => array(
                0 => 'stockapp_bn',
                1 => 'pickinglist_bn',
                2 => 'status',
                3 => 'operator',
                4 => 'create_time',
                5 => 'remark',
                6 => 'sumqty',
            ),
            'default_in_list' => array(
                0 => 'stockapp_bn',
                1 => 'pickinglist_bn',
                2 => 'status',
                3 => 'operator',
                4 => 'create_time',
                5 => 'remark',
                6 => 'sumqty',
            ),
        );
        return $schema;
    }



    public function getExportTitle($fields)
    {
        $title = array();
        $main_columns = $this->get_schema_export();
        foreach (explode(',', $fields) as $k => $col) {
            if (isset($main_columns['columns'][$col])) {
                $title[] = "*:" . $main_columns['columns'][$col]['label'];
            }
        }

        return mb_convert_encoding(implode(',', $title), 'GBK', 'UTF-8');
    }

}
